<template>
	<a-form ref="formRef" :model="addFormData" class="add_modal"
		:rules="rules">
		<div class="items">
			<div style="width:100%">
				<p>角色名称<span class="my_required">*</span></p>
				<a-form-item name="name">
					<MyInput :modelV="addFormData.name" @submit="addFormData.name = $event" :maxlength="20" />
				</a-form-item>
			</div>
		</div>
		<div class="items">
			<div style="width:100%">
				<p>角色描述</p>
				<a-form-item name="remark">
					<a-textarea :rows="8" row-height="32px" :maxlength="200" v-model:value="addFormData.remark" />
				</a-form-item>
			</div>
		</div>
		<div style="padding-left: 80px;" class="magTop10">
			<MyButton class="reaset" @click="shareRole" title="权限分配" />
		</div>
		<div class="bottom-btn">
			<MyButton class="reaset" @click="$emit('onClose')" title="取消" />
			<MyButton class="submit" @click="onSubmit" title="保存" />
		</div>
	</a-form>
</template>

<script lang="ts" setup>
	import { ref, watch } from 'vue';
	import cloneDeep from 'lodash/cloneDeep';
	import { useOrganization } from '@/store';
	import { createRole,updateRole } from "@/api/orang";
	import Message from "@/utils/message";
			
	const PROPS = defineProps({
	  formData: {
	    type: Object,
	    default: {},
	  },
	});
	const organizationStore = useOrganization();
	const EMITS = defineEmits(["onClose","shareRole","success"]);
	
	const formRef = ref();
	const addFormData = ref<any>({});
	const rules = {
	  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
	};
	
	const onSubmit = ()=>{
		formRef.value.validate().then(async () => {
			let power_ids = '';
			// if(addFormData.value.power){
			// 	const { api, route } = addFormData.value.power;
			// 	const arr = api.concat(route);
			// 	arr.forEach((item,index)=>{
			// 		if(index == arr.length - 1){
			// 			power_ids += item;
			// 		}else{
			// 			power_ids += item +',';
			// 		}
			// 	});
			// }
			console.log(addFormData.value)
			if(addFormData.value.id){
				const res = await updateRole({ ...addFormData.value,power_ids });
				if(!res) return;
				// organizationStore.getRoleList(true);
				Message.success("更新角色成功");
				EMITS('success');
			}else{
				const res = await createRole({ ...addFormData.value,power_ids });
				if(!res) return;
				// organizationStore.getRoleList(true);
				Message.success("新增角色成功");
				EMITS('success');
			}
		}).catch((error: ValidateErrorEntity < FormState > ) => {
			console.log('error', error);
		});
	};
	
	
	const shareRole = ()=>{
		if(!addFormData.value.title || addFormData.value.title == '') return Message.warning('请先输入角色名称');
		EMITS('shareRole', addFormData.value.title);
	};
	
	watch(()=>PROPS.formData,()=>{
		addFormData.value = cloneDeep({ ...addFormData.value,...PROPS.formData });
	},{ deep:true, immediate:true });
	
</script>

<style lang="less" scoped>
	@import './index.less';
</style>
